import 'package:eplorex/providers/user_context.dart';
import 'package:flutter/material.dart';

import '../../dao/conversation_dao.dart';
import '../../dao/follow_dao.dart';
import '../../dao/user_profile_dao.dart';
import '../../models/follow/userprofile_model.dart';
import '../message/message_conversation.dart';

class UserProfilePage extends StatefulWidget {
  const UserProfilePage({super.key, required this.userId});

  final num userId;

  @override
  State<UserProfilePage> createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<UserProfilePage> {
  late Future<UserProfileModel> _followModel;
  late int _followStat; // 0-未初始化 1- 已关注 2- 陌生人

  @override
  void initState() {
    super.initState();
    _followStat = 0;
    _followModel = UserProfileDao.queryUserProfile(widget.userId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(),
      ),
      body: Container(
          // padding: EdgeInsets.only(top: 10),
          child: ListView(
            children: [
              getHeader(),
            ],
          )),
    );
  }

  Widget getHeader() {
    return Container(
      color: Colors.white,
      height: 200,
      child: FutureBuilder(
        future: _followModel,
        builder:
            (BuildContext context, AsyncSnapshot<UserProfileModel> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting ||
              snapshot.connectionState == ConnectionState.done &&
                  snapshot.data == null) {
            return const Center(
              child: Text("loading....."),
            );
          }
          UserProfileModel model = snapshot.data!;
          if (_followStat == 0) {
            _followStat = (model.relation == 1 || model.relation == 5) ? 1 : 2;
          }
          return Container(
            // color: Colors.red,
            child: Container(
              margin: EdgeInsets.only(left: 20, right: 10, bottom: 20),
              padding: EdgeInsets.only(top: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    // width: 200,
                    child: Flex(
                      // direction: Axis.horizontal,
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      direction: Axis.horizontal,
                      children: [
                        CircleAvatar(
                          radius: 40,
                          backgroundImage: NetworkImage(model.avatar!),
                        ),
                        SizedBox(
                          width: 20,
                        ),
                        Container(
                          // height: 60,
                          child: Column(
                            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                child: Text(
                                  "账号名称",
                                  style: TextStyle(fontSize: 20),
                                ),
                              ),
                              Container(
                                child: Row(
                                  // spacing: 10,
                                  children: [
                                    Text(
                                      "账号名称:",
                                      style: TextStyle(fontSize: 16),
                                    ),
                                    Text(
                                      model.userName!,
                                      style: TextStyle(fontSize: 16),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  const SizedBox(
                    height: 40,
                  ),
                  Flex(direction: Axis.horizontal, children: [
                    Expanded(
                      flex: 2,
                      child: Wrap(
                        spacing: 16,
                        children: [
                          Container(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('${model.fansCnt}',
                                    style: const TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 18)),
                                const Text(
                                  "粉丝",
                                  style: TextStyle(color: Colors.grey),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('${model.followCnt}',
                                    style: const TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 18)),
                                const Text(
                                  "关注",
                                  style: TextStyle(color: Colors.grey),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: const Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text("2",
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 18)),
                                Text(
                                  "收藏",
                                  style: TextStyle(color: Colors.grey),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                        flex: 2,
                        child: _getFollowButton(model.userId!, context))
                  ])
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _getFollowButton(num userId, BuildContext context) {
    return _followStat == 2
        ? FilledButton(
            onPressed: () {
              FollowDao.followUser(userId, true);
              setState(() {
                _followStat = 1;
              });
            },
            child: Text("关注"),
          )
        : Row(
            // spacing: 10,
            children: [
              OutlinedButton(
                style: ButtonStyle(
                    minimumSize: MaterialStateProperty.all(Size(80, 30)),
                    padding: MaterialStateProperty.all(EdgeInsets.zero)),
                onPressed: () {
                  _showBottomSheet(context, userId);
                },
                child: const Row(
                  children: [
                    Text("已关注"),
                    Icon(
                      Icons.arrow_drop_down,
                      size: 20,
                    )
                  ],
                ),
              ),
              const SizedBox(
                width: 8,
              ),
              FilledButton(
                style: ButtonStyle(
                    minimumSize: MaterialStateProperty.all(Size(60, 30)),
                    padding: MaterialStateProperty.all(EdgeInsets.zero)),
                onPressed: () {
                  _enterChat(context, userId);
                },
                child: const Text("聊天"),
              )
            ],
          );
  }

  void _enterChat(BuildContext context, num userId) {
    ConversationDao.getUserPairConversation(UserContext.cxt()!.uid, userId)
        .then((conv) => {
              if (conv != null)
                {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (_) => ConversationDetailPage(
                          conv!.convName!,
                          conv.cid,
                          conv.senderId!.toInt(),
                          conv.partnerId!.toInt())))
                }
            });
  }

  void _showBottomSheet(BuildContext context, num userId) {
    showBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 180,
            margin: EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text("操作"),
                    IconButton(
                        onPressed: () => {Navigator.pop(context)},
                        icon: Icon(Icons.close))
                  ],
                ),
                Expanded(
                    child: Container(
                  // margin: EdgeInsets.all(10),
                  color: Colors.white,
                  child: ListView(
                    children: [
                      ListTile(
                        // leading: Icon(Icons.keyboard_option_key),
                        title: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [Text('分组'), Icon(Icons.group)],
                        ),
                        onTap: () => {},
                      ),
                      ListTile(
                        // leading: Icon(Icons.keyboard_option_key),
                        title: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '取消关注',
                              style: TextStyle(color: Colors.red),
                            ),
                            Icon(Icons.delete)
                          ],
                        ),
                        onTap: () {
                          FollowDao.followUser(userId, false);
                          Navigator.pop(context);
                          setState(() {
                            _followStat = 2;
                          });
                        },
                      ),
                    ],
                  ),
                ))
              ],
            ),
          );
        });
  }
}
